<template>
  <s-clean-layout :title="isAdd ? '添加还款记录' : '编辑还款记录'" navbar="normal">
    <view class="repayment-edit-container">
      <!-- 表单内容 -->
      <view class="form-container">
        <!-- 金额输入 -->
        <view class="form-item">
          <view class="form-label">金额</view>
          <input 
            type="digit" 
            v-model="formData.amount" 
            placeholder="请输入金额" 
            class="item-input"
          />
        </view>
        
        <!-- 还款日期选择 -->
        <view class="form-item" @tap="selectDate">
          <view class="form-label">还款日期</view>
          <view class="item-value">
            <text class="date-value">{{ formData.repaymentDate }}</text>
            <uni-icons type="right" size="16" color="#CCCCCC"></uni-icons>
          </view>
        </view>
        
        <!-- 还款方式选择 -->
        <view class="form-item" @tap="selectRepaymentMethod">
          <view class="form-label">还款方式</view>
          <view class="item-value">
            <text class="method-value">{{ getRepaymentMethodText(formData.repaymentMethod) }}</text>
            <uni-icons type="right" size="16" color="#CCCCCC"></uni-icons>
          </view>
        </view>
        
        <!-- 账户类型选择 -->
        <view class="form-item" @tap="selectAccountType">
          <view class="form-label">账户类型</view>
          <view class="item-value">
            <text class="account-value">{{ getAccountTypeText(formData.accountType) }}</text>
            <uni-icons type="right" size="16" color="#CCCCCC"></uni-icons>
          </view>
        </view>
        
        <!-- 备注输入 -->
        <view class="form-item">
          <view class="form-label">备注</view>
          <textarea 
            v-model="formData.remark" 
            placeholder="请输入备注信息" 
            class="item-textarea"
          />
        </view>
      </view>
      
      <!-- 底部操作栏 -->
      <view class="bottom-bar" v-if="!isAdd">
        <view class="action-btn delete-btn" @tap="deleteRecord">删除</view>
        <view class="action-btn save-btn" @tap="saveRecord">保存</view>
      </view>
      
      <!-- 添加模式下的底部保存按钮 -->
      <view class="bottom-bar" v-if="isAdd">
        <view class="action-btn save-btn full-width" @tap="saveRecord">保存</view>
      </view>
      
      <!-- 日期选择器 -->
      <s-datetime-picker
        v-model:visible="showDatePicker"
        :initialDate="formData.repaymentDate"
        mode="date"
        title="选择日期"
        @confirm="handleDateConfirm"
      />
      
      <!-- 还款方式选择器 -->
      <s-dropdown-selector
        v-model:visible="showMethodSelector"
        title="选择还款方式"
        :options="repaymentMethodOptions"
        v-model="selectedMethod"
        @confirm="handleMethodConfirm"
      />
      
      <!-- 账户类型选择器 -->
      <s-dropdown-selector
        v-model:visible="showAccountSelector"
        title="选择账户类型"
        :options="accountOptions"
        v-model="selectedAccount"
        @confirm="handleAccountConfirm"
      />
    </view>
  </s-clean-layout>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import BorrowApi from '@/pages/money/api/borrow';

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 页面参数
const isAdd = ref(true);
const recordId = ref(0);
const borrowRecordId = ref(0);

// 表单数据
const formData = ref({
  id: null,
  borrowRecordId: null,
  repaymentDate: formatDate(new Date()),
  repaymentMethod: 1, // 1-现金，2-转账，3-其他
  accountType: 'WCHAT', // 默认微信
  amount: '',
  remark: ''
});

// 选择器相关
const showDatePicker = ref(false);
const showMethodSelector = ref(false);
const showAccountSelector = ref(false);
const selectedMethod = ref('');
const selectedAccount = ref('');

// 还款方式选项
const repaymentMethodOptions = ['现金', '转账', '其他'];

// 账户类型选项
const accountOptions = ['微信', '支付宝', '现金', '银行卡', '其他'];

// 账户类型映射
const accountTypeMap = {
  '微信': 'WCHAT',
  '支付宝': 'ALIPAY',
  '现金': 'MONEY',
  '银行卡': 'BANK_CARD',
  '其他': 'OTHER'
};

// 账户类型反向映射
const accountTypeReverseMap = {
  'WCHAT': '微信',
  'ALIPAY': '支付宝',
  'MONEY': '现金',
  'BANK_CARD': '银行卡',
  'OTHER': '其他'
};

// 页面加载时获取参数
onMounted(() => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const { id, borrowRecordId: borrowId } = currentPage.options;
  
  if (id) {
    isAdd.value = false;
    recordId.value = id;
    fetchRecordDetail(id);
  }
  
  if (borrowId) {
    borrowRecordId.value = borrowId;
    formData.value.borrowRecordId = borrowId;
  }
});

// 获取记录详情
const fetchRecordDetail = async (id) => {
  try {
    const response = await BorrowApi.queryRepayRecordDetail({ id: Number(id) });
    
    if (response.code === 0 && response.data) {
      const record = response.data;
      formData.value = {
        id: record.id,
        borrowRecordId: record.borrowRecordId,
        repaymentDate: formatDate(record.repaymentDate),
        repaymentMethod: record.repaymentMethod,
        accountType: record.accountType,
        amount: record.amount,
        remark: record.remark || ''
      };
    } else {
      uni.showToast({
        title: response.msg || '获取记录详情失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取记录详情失败:', error);
    uni.showToast({
      title: '获取记录详情失败',
      icon: 'none'
    });
  }
};

// 选择日期
const selectDate = () => {
  showDatePicker.value = true;
};

// 处理日期选择确认
const handleDateConfirm = (result) => {
  if (result && result.date) {
    formData.value.repaymentDate = result.date;
  }
};

// 选择还款方式
const selectRepaymentMethod = () => {
  selectedMethod.value = getRepaymentMethodText(formData.value.repaymentMethod);
  showMethodSelector.value = true;
};

// 处理还款方式选择确认
const handleMethodConfirm = (method) => {
  const methodMap = {
    '现金': 1,
    '转账': 2,
    '其他': 3
  };
  formData.value.repaymentMethod = methodMap[method] || 1;
};

// 选择账户类型
const selectAccountType = () => {
  selectedAccount.value = getAccountTypeText(formData.value.accountType);
  showAccountSelector.value = true;
};

// 处理账户类型选择确认
const handleAccountConfirm = (account) => {
  formData.value.accountType = accountTypeMap[account] || 'WCHAT';
};

// 获取还款方式文本
const getRepaymentMethodText = (method) => {
  const methodMap = {
    1: '现金',
    2: '转账',
    3: '其他'
  };
  return methodMap[method] || '其他';
};

// 获取账户类型文本
const getAccountTypeText = (type) => {
  return accountTypeReverseMap[type] || '其他';
};

// 保存记录
const saveRecord = async () => {
  // 表单验证
  if (!formData.value.amount) {
    uni.showToast({
      title: '请输入金额',
      icon: 'none'
    });
    return;
  }
  
  if (!formData.value.repaymentDate) {
    uni.showToast({
      title: '请选择还款日期',
      icon: 'none'
    });
    return;
  }
  
  try {
    uni.showLoading({
      title: '保存中...'
    });
    
    const params = {
      id: formData.value.id,
      borrowRecordId: formData.value.borrowRecordId,
      repaymentDate: formData.value.repaymentDate,
      repaymentMethod: formData.value.repaymentMethod,
      accountType: formData.value.accountType,
      amount: parseFloat(formData.value.amount),
      remark: formData.value.remark
    };
    
    const response = await BorrowApi.addOrUpdateRepayRecord(params);
    
    uni.hideLoading();
    
    if (response.code === 0) {
      uni.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 1500,
        success: () => {
          // 设置需要刷新的标记
          uni.setStorageSync('repaymentListNeedRefresh', true);
          // 跳转回还款记录列表页面
          uni.redirectTo({
            url: `/pages/money/repayment-list?borrowRecordId=${borrowRecordId.value}`
          });
        }
      });
    } else {
      uni.showToast({
        title: response.msg || '保存失败',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error('保存记录失败:', error);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
  }
};

// 删除记录
const deleteRecord = () => {
  uni.showModal({
    title: '提示',
    content: '确定要删除这条还款记录吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({
            title: '删除中...'
          });
          
          const response = await BorrowApi.deleteRepayRecord({ id: Number(recordId.value) });
          
          uni.hideLoading();
          
          if (response.code === 0) {
            uni.showToast({
              title: '删除成功',
              icon: 'success',
              duration: 1500,
              success: () => {
                // 设置需要刷新的标记
                uni.setStorageSync('repaymentListNeedRefresh', true);
                // 跳转回还款记录列表页面
                uni.redirectTo({
                  url: `/pages/money/repayment-list?borrowRecordId=${borrowRecordId.value}`
                });
              }
            });
          } else {
            uni.showToast({
              title: response.msg || '删除失败',
              icon: 'none'
            });
          }
        } catch (error) {
          uni.hideLoading();
          console.error('删除记录失败:', error);
          uni.showToast({
            title: '网络异常，请稍后重试',
            icon: 'none'
          });
        }
      }
    }
  });
};

// 移除不再需要的goBack方法
// const goBack = () => {
//   uni.navigateBack();
// };
</script>

<style lang="scss" scoped>
.repayment-edit-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-top: 20rpx; /* 添加顶部间距 */
  padding-bottom: 120rpx; /* 为底部操作栏留出空间 */
  position: relative;
}

/* 移除原有的导航栏样式 */
.header {
  display: none;
}

.left {
  display: none;
}

.title {
  display: none;
}

.right {
  display: none;
}

.form-container {
  padding: 0 0 30rpx;
}

.form-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  background-color: #fff;
  margin-bottom: 2rpx;
  position: relative;
}

.form-label {
  width: 200rpx;
  font-size: 32rpx;
  color: #333;
}

.item-value {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.date-value, .method-value, .account-value {
  font-size: 32rpx;
  color: #666;
  margin-right: 10rpx;
}

.item-input {
  flex: 1;
  height: 80rpx;
  font-size: 32rpx;
  color: #333;
  text-align: right;
}

.item-textarea {
  flex: 1;
  height: 160rpx;
  font-size: 32rpx;
  color: #333;
  text-align: right;
}

/* 添加底部操作栏样式 */
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  height: 100rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 100;
  padding: 20rpx;
}

.action-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  height: 100%;
  border-radius: 50rpx;
  margin: 0 10rpx;
  transition: all 0.3s ease;
}

.delete-btn {
  background-color: #fff;
  color: #ff6b6b;
  border: 1px solid #ff6b6b;
}

.save-btn {
  background-color: #007AFF;
  color: #fff;
  box-shadow: 0 4rpx 12rpx rgba(0, 123, 255, 0.3);
}

.full-width {
  width: 100%;
  margin: 0 20rpx;
}
</style>